<template>
  <div class="post-list">
    <h1>答疑讨论区</h1>
    <p>发表任何想与大家分享的经验及想法！</p>
    <button class="primary-button" @click="openPostDialog">发起主题</button>

    <!-- 搜索框 -->
    <div class="search-bar">
      <input
          type="text"
          v-model="searchQuery"
          placeholder="搜索帖子内容或标题"
          class="search-input"
      />
      <button @click="searchPosts" class="search-button">🔍</button>
    </div>

    <!-- 自定义对话框 -->
    <div v-if="showPostDialog" class="custom-dialog-overlay" @click.self="closePostDialog">
      <div class="custom-dialog">
        <h2>发起新主题</h2>
        <form @submit.prevent="submitPost" class="dialog-form">
          <div class="form-group">
            <label for="title">标题</label>
            <input id="title" type="text" v-model="newPost.title" placeholder="请输入标题" required />
          </div>

          <div class="form-group">
            <label for="content">内容</label>
            <textarea id="content" v-model="newPost.content" placeholder="请输入内容" rows="5" required></textarea>
          </div>


          <div class="dialog-footer">
            <button type="button" class="secondary-button" @click="closePostDialog">取消</button>
            <button type="submit" class="primary-button">发布主题</button>
          </div>
        </form>
      </div>
    </div>

    <!-- 帖子列表 -->
    <div class="post-table">
      <div class="post-header">
        <span>全部主题</span>
      </div>

      <div v-for="post in posts" :key="post.id" class="post-item" @click="goToPostDetail(post.post_id)">
        <h3 class="post-title">{{ post.title }}</h3>
        <p class="post-author">
          {{ post.stu_id }} 发表于 {{ post.createdAt }}
        </p>
        <div class="post-stats">
          <span>收藏: {{ post.favorites }}</span>
        </div>
      </div>
    </div>
  </div>
</template>


<script>
import axios from 'axios';
import { BASE_URL } from '@/config';

export default {
  props: {
    course_id: {
      type: Number,
      required: true,
    },
  },
  data() {
    return {
      posts: [],
      showPostDialog: false,
      searchQuery: '', // 搜索关键词
      newPost: {
        title: '',
        content: '',
        images: []
      }
    };
  },
  created() {
    this.fetchPosts(); // 页面加载时获取所有帖子
  },
  methods: {
    fetchPosts() {
      axios.post(`${BASE_URL}/posts/postList`, { course_id: this.course_id })
          .then(response => {
            if (response.data.code === 200) {
              this.posts = response.data.data;
            } else {
              console.error('获取帖子信息失败:', response.data.message);
            }
          })
          .catch(error => {
            console.error('请求失败:', error);
          });
    },

    // 搜索帖子
    searchPosts() {
      axios.post(`${BASE_URL}/posts/search`, {
        course_id: this.course_id,
        s: this.searchQuery
      })
          .then(response => {
            if (response.data.code === 200) {
              this.posts = response.data.data; // 更新 posts 显示搜索结果
              this.$message.success('搜索完成');
            } else {
              this.$message.error('搜索失败');
            }
          })
          .catch(error => {
            console.error('搜索请求失败:', error);
            this.$message.error('搜索请求失败');
          });
    },

    openPostDialog() {
      this.showPostDialog = true;
    },

    closePostDialog() {
      this.showPostDialog = false;
    },

    handleImageUpload(event) {
      const files = Array.from(event.target.files);
      this.newPost.images = files.map(file => URL.createObjectURL(file));
    },

    goToPostDetail(postId) {
      if (!postId) {
        console.error('postId is missing');
        return;
      }
      this.$router.push(`/PostDetail/${postId}`)
    },

    submitPost() {
      const stu_id = window.sessionStorage.getItem('userId');
      console.log(stu_id);
      const postData = {
        stu_id: stu_id,
        course_id: this.course_id,
        title: this.newPost.title,
        content: this.newPost.content,
        images: this.newPost.images
      };
      axios.post(`${BASE_URL}/posts/createPost`, postData)
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success('发帖成功');
              this.showPostDialog = false;
              this.fetchPosts();
            } else {
              this.$message.error('发帖失败');
            }
          })
          .catch(error => {
            console.error('发帖请求失败:', error);
            this.$message.error('发帖请求失败');
          });
    }
  }
};
</script>
<style scoped>
.post-list {
  padding: 20px;
}

.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.search-input {
  width: 100%;
  padding: 10px;
  border-radius: 4px;
  border: 1px solid #ccc;
  font-size: 16px;
}

.search-button {
  padding: 10px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.search-button:hover {
  background-color: #66b1ff;
}

/* 给“发起主题”按钮和搜索框增加间距 */
.primary-button {
  margin-right: 15px;
}

.primary-button, .secondary-button {
  padding: 8px 16px;
  border: none;
  cursor: pointer;
  font-size: 16px;

}

.primary-button {
  background-color: #409eff;
  color: white;
}

.secondary-button {
  background-color: #f0f0f0;
  color: #333;
}

.primary-button:hover {
  background-color: #66b1ff;
}

.secondary-button:hover {
  background-color: #e0e0e0;
}

.post-table {
  margin-top: 20px;
}

.post-header {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 2px solid #eee;
}

.post-item {
  padding: 15px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
}

.post-item:hover {
  background-color: #f9f9f9;
}

.custom-dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.custom-dialog {
  background: white;
  padding: 20px;
  width: 400px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
}

.dialog-form {
  display: flex;
  flex-direction: column;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  font-weight: bold;
  margin-bottom: 5px;
  display: block;
}

.form-group input[type="text"],
.form-group textarea,
.form-group input[type="file"] {
  width: 100%;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.post-title {
  font-size: 18px;
  color: #333;
  margin: 0;
}

.post-author {
  font-size: 14px;
  color: #888;
  margin-top: 5px;
}

.post-stats {
  font-size: 14px;
  color: #888;
  display: flex;
  gap: 10px;
  margin-top: 5px;
}
</style>
